/*

������������������USER A������������������� 

*/

import java.io.*;
import java.net.*;
import java.util.*;



public class NS9_userA {
    
    public static int find_pow(int a, int b,int c) {
        int i,final_ans=1;
        for(i=0;i<b;i++)
            final_ans=(final_ans*(a%c))%c;
        return final_ans%c;
    }
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter value of P");
        int P = sc.nextInt();
        
        System.out.println("Enter value of a");
        int a = sc.nextInt();

        System.out.println("Enter value of Xa");
        int Xa = sc.nextInt();

        int Ya;
        Ya=find_pow(a,Xa,P);
        
        ServerSocket ss = null;
        Socket s = null;
        ss = new ServerSocket(7777);
        s = ss.accept();
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        DataInputStream dis = new DataInputStream(s.getInputStream());

        dos.writeUTF(Integer.toString(Ya));
        String Yb = dis.readUTF();
            
        int k;
        k=find_pow(Integer.parseInt(Yb),Xa,P);
            
        System.out.println("Key is "+k);
        
    }
}


/*

������������������USER B������������������� 

*/

import java.io.*;
import java.net.*;
import java.util.*;



public class NS9_userB{
    
    public static int find_pow(int a, int b,int c) {
        int i,final_ans=1;
        for(i=0;i<b;i++)
            final_ans=(final_ans*(a%c))%c;
        return final_ans%c;
    }
    
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter value of P");
        int P = sc.nextInt();
        
        System.out.println("Enter value of a");
        int a = sc.nextInt();

        
        System.out.println("Enter value of Xb");
        int Xb = sc.nextInt();
        
        int Yb;
        Yb=find_pow(a,Xb,P);

        
        Socket s = null;
        s = new Socket("127.0.0.1",7777);
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        DataInputStream dis = new DataInputStream(s.getInputStream());
        
        String Ya = dis.readUTF();
        dos.writeUTF(Integer.toString(Yb));

        int k;
        k=find_pow(Integer.parseInt(Ya),Xb,P);
            
        System.out.println("Key is "+k);
    }
    
}

/*

OUTPUT:-

Shripad-Ashtekars-MacBook-Pro:NS9 shripadashtekar$ javac NS9_userA.java 
Shripad-Ashtekars-MacBook-Pro:NS9 shripadashtekar$ java NS9_userA
Enter value of P
353
Enter value of a
3
Enter value of Xa
97
Key is 160

Shripad-Ashtekars-MacBook-Pro:NS9 shripadashtekar$ javac NS9_userB.java 
Shripad-Ashtekars-MacBook-Pro:NS9 shripadashtekar$ java NS9_userB
Enter value of P
353
Enter value of a
3
Enter value of Xb
233
Key is 160


*/